﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Net;
/// <summary>
/// Error logger
/// </summary>
/// 
namespace Shut {
	public class ErrorLogger
	{
		protected static readonly string ErrorLog = HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings.Get("ErrorLog"));

		
		protected static string GetBrowser()
		{
			// return information about browser
			HttpBrowserCapabilities br = HttpContext.Current.Request.Browser;
			string ret = "Cookies enabled = " + br.Cookies.ToString();
			ret += "\nIs Crawler = " + br.Crawler.ToString();
			ret += "\nIs Mobile = " + br.IsMobileDevice;
			ret += "\nJavascript = " + br.EcmaScriptVersion.Major;
			ret += "\nMajor Version = " + br.MajorVersion.ToString() + " " + br.MinorVersionString;
			ret += "\nMobile Device = " + br.MobileDeviceManufacturer + " " + br.MobileDeviceModel;
			ret += "\nPlatform = " + br.Platform;
			ret += "\nCss = " + br.SupportsCss;
			ret += "\nType = " + br.Type;
			ret += "\nVersion = " + br.Version;
			ret += "\nUser Agent = " + HttpContext.Current.Request.UserAgent;
			ret += "\nHost Address = " + HttpContext.Current.Request.UserHostAddress + " Name: " + HttpContext.Current.Request.UserHostName;
			ret += "\nReferrer = " + HttpContext.Current.Request.UrlReferrer;
			ret += "\nCurrent Execution File Path= " + HttpContext.Current.Request.CurrentExecutionFilePath;

			return ret;
		}
		public static void LogError()
		{
			// log a general unknown error
			LogError("nothing real","Unknown");
		}
		
		public static void LogError(string message, string fullmessage){
			HttpContext context = HttpContext.Current;
			try
			{

				XmlDocument doc = new XmlDocument();
				doc.Load(ErrorLog);
				XmlNode root = doc.DocumentElement;
				XmlElement E = doc.CreateElement("error");

				E.InnerXml = String.Format("<date>{0}</date><message>{1}</message><full><![CDATA[{2}]]></full><browser><![CDATA[{3}]]></browser>",
					DateTime.Now.ToUniversalTime().ToString(),
					message,
					context.Server.HtmlEncode(fullmessage),
					GetBrowser());

				root.AppendChild(E);

				doc.Save(ErrorLogger.ErrorLog);


			}
			catch (WebException ex)
			{
				// let parent redirect silently	 (TODO: make a special error page that fires some event that event log isnt found or soemthing)

				HttpContext.Current.Response.Write(ex.Message);

			}
		}

	}
}